text:
001
018
019    package org.apache.hadoop.hdfs.server.common;
020
021    import com.google.common.base.Charsets;
022
023    import org.apache.commons.logging.Log;
024    import org.apache.commons.logging.LogFactory;
025    import org.apache.hadoop.classification.InterfaceAudience;
026    import org.apache.hadoop.conf.Configuration;
027    import org.apache.hadoop.fs.Path;
028    import org.apache.hadoop.hdfs.BlockReader;
029    import org.apache.hadoop.hdfs.BlockReaderFactory;
030    import org.apache.hadoop.hdfs.DFSClient;
031    import org.apache.hadoop.hdfs.DFSUtil;
032    import org.apache.hadoop.hdfs.net.TcpPeerServer;
033    import org.apache.hadoop.hdfs.protocol.*;
034    import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
035    import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
036    import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
037    import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
038    import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
039    import org.apache.hadoop.hdfs.server.namenode.NameNode;
040    import org.apache.hadoop.hdfs.server.namenode.NameNodeHttpServer;
041    import org.apache.hadoop.hdfs.web.resources.DelegationParam;
042    import org.apache.hadoop.hdfs.web.resources.DoAsParam;
043    import org.apache.hadoop.hdfs.web.resources.UserParam;
044    import org.apache.hadoop.http.HtmlQuoting;
045    import org.apache.hadoop.io.IOUtils;
046    import org.apache.hadoop.net.NetUtils;
047    import org.apache.hadoop.security.AccessControlException;
048    import org.apache.hadoop.security.SecurityUtil;
049    import org.apache.hadoop.security.UserGroupInformation;
050    import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
051    import org.apache.hadoop.security.authentication.util.KerberosName;
052    import org.apache.hadoop.security.authorize.ProxyUsers;
053    import org.apache.hadoop.security.token.Token;
054    import org.apache.hadoop.util.VersionInfo;
055
056    import javax.servlet.ServletContext;
057    import javax.servlet.http.HttpServletRequest;
058    import javax.servlet.jsp.JspWriter;
059
060    import java.io.ByteArrayInputStream;
061    import java.io.DataInputStream;
062    import java.io.IOException;
063    import java.io.UnsupportedEncodingException;
064    import java.net.InetSocketAddress;
065    import java.net.Socket;
066    import java.net.URL;
067    import java.net.URLEncoder;
068    import java.util.*;
069
070    import static org.apache.hadoop.fs.CommonConfigurationKeys.DEFAULT_HADOOP_HTTP_STATIC_USER;
071    import static org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_HTTP_STATIC_USER;
072
073    @InterfaceAudience.Private
074    public class JspHelper {
075      public static final String CURRENT_CONF = "current.conf";
076      public static final String DELEGATION_PARAMETER_NAME = DelegationParam.NAME;
077      public static final String NAMENODE_ADDRESS = "nnaddr";
078      static final String SET_DELEGATION = "&" + DELEGATION_PARAMETER_NAME +
079                                                  "=";
080      private static final Log LOG = LogFactory.getLog(JspHelper.class);
081
082      /** Private constructor for preventing creating JspHelper object. */
083      private JspHelper() {}
084
085      // data structure to count number of blocks on datanodes.
086      private static class NodeRecord extends DatanodeInfo {
087        int frequency;
088
089        public NodeRecord(DatanodeInfo info, int count) {
090          super(info);
091          this.frequency = count;
092        }
093
094        @Override
095        public boolean equals(Object obj) {
096          // Sufficient to use super equality as datanodes are uniquely identified
097          // by DatanodeID
098          return (this == obj) || super.equals(obj);
099        }
100        @Override
101        public int hashCode() {
102          // Super implementation is sufficient
103          return super.hashCode();
104        }
105      }
106
107      // compare two records based on their frequency
108      private static class NodeRecordComparator implements Comparator<NodeRecord> {
109
110        @Override
111        public int compare(NodeRecord o1, NodeRecord o2) {
112          if (o1.frequency < o2.frequency) {
113            return -1;
114          } else if (o1.frequency > o2.frequency) {
115            return 1;
116          }
117          return 0;
118        }
119      }
120
121      /**
122       * convenience method for canonicalizing host name.
123       * @param addr name:port or name
124       * @return canonicalized host name
125       */
126       public static String canonicalize(String addr) {
127        // default port 1 is supplied to allow addr without port.
128        // the port will be ignored.
129        return NetUtils.createSocketAddr(addr, 1).getAddress()
130               .getCanonicalHostName();
131      }
132
133      /**
134       * A helper class that generates the correct URL for different schema.
135       *
136       */
137      public static final class Url {
138        public static String authority(String scheme, DatanodeID d) {
139          String fqdn = canonicalize(d.getIpAddr());
140          if (scheme.equals("http")) {
141            return fqdn + ":" + d.getInfoPort();
142          } else if (scheme.equals("https")) {
143            return fqdn + ":" + d.getInfoSecurePort();
144          } else {
145            throw new IllegalArgumentException("Unknown scheme:" + scheme);
146          }
147        }
148
149        public static String url(String scheme, DatanodeID d) {
150          return scheme + "://" + authority(scheme, d);
151        }
152      }
153
154      public static DatanodeInfo bestNode(LocatedBlocks blks, Configuration conf)
155          throws IOException {
156        HashMap<DatanodeInfo, NodeRecord> map =
157          new HashMap<DatanodeInfo, NodeRecord>();
158        for (LocatedBlock block : blks.getLocatedBlocks()) {
159          DatanodeInfo[] nodes = block.getLocations();
160          for (DatanodeInfo node : nodes) {
161            NodeRecord record = map.get(node);
162            if (record == null) {
163              map.put(node, new NodeRecord(node, 1));
164            } else {
165              record.frequency++;
166            }
167          }
168        }
169        NodeRecord[] nodes = map.values().toArray(new NodeRecord[map.size()]);
170        Arrays.sort(nodes, new NodeRecordComparator());
171        return bestNode(nodes, false, conf);
172      }
173
174      public static DatanodeInfo bestNode(LocatedBlock blk, Configuration conf)
175          throws IOException {
176        DatanodeInfo[] nodes = blk.getLocations();
177        return bestNode(nodes, true, conf);
178      }
179
180      public static DatanodeInfo bestNode(DatanodeInfo[] nodes, boolean doRandom,
181          Configuration conf) throws IOException {
182        TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
183        DatanodeInfo chosenNode = null;
184        int failures = 0;
185        Socket s = null;
186        int index = -1;
187        if (nodes == null || nodes.length == 0) {
188          throw new IOException("No nodes contain this block");
189        }
190        while (s == null) {
191          if (chosenNode == null) {
192            do {
193              if (doRandom) {
194                index = DFSUtil.getRandom().nextInt(nodes.length);
195              } else {
196                index++;
197              }
198              chosenNode = nodes[index];
199            } while (deadNodes.contains(chosenNode));
200          }
201          chosenNode = nodes[index];
202
203          //just ping to check whether the node is alive
204          InetSocketAddress targetAddr = NetUtils.createSocketAddr(
205              chosenNode.getInfoAddr());
206
207          try {
208            s = NetUtils.getDefaultSocketFactory(conf).createSocket();
209            s.connect(targetAddr, HdfsServerConstants.READ_TIMEOUT);
210            s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
211          } catch (IOException e) {
212            deadNodes.add(chosenNode);
213            IOUtils.closeSocket(s);
214            s = null;
215            failures++;
216          }
217          if (failures == nodes.length)
218            throw new IOException("Could not reach the block containing the data. Please try again");
219
220        }
221        s.close();
222        return chosenNode;
223      }
224
225      public static void streamBlockInAscii(InetSocketAddress addr, String poolId,
226          long blockId, Token<BlockTokenIdentifier> blockToken, long genStamp,
227          long blockSize, long offsetIntoBlock, long chunkSizeToView,
228          JspWriter out, Configuration conf, DFSClient.Conf dfsConf,
229          DataEncryptionKey encryptionKey)
230              throws IOException {
231        if (chunkSizeToView == 0) return;
232        Socket s = NetUtils.getDefaultSocketFactory(conf).createSocket();
233        s.connect(addr, HdfsServerConstants.READ_TIMEOUT);
234        s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
235
236        int amtToRead = (int)Math.min(chunkSizeToView, blockSize - offsetIntoBlock);
237
238          // Use the block name for file name.
239        String file = BlockReaderFactory.getFileName(addr, poolId, blockId);
240        BlockReader blockReader = BlockReaderFactory.newBlockReader(dfsConf, file,
241            new ExtendedBlock(poolId, blockId, 0, genStamp), blockToken,
242            offsetIntoBlock, amtToRead,  true,
243            "JspHelper", TcpPeerServer.peerFromSocketAndKey(s, encryptionKey),
244            new DatanodeID(addr.getAddress().getHostAddress(),
245                addr.getHostName(), poolId, addr.getPort(), 0, 0, 0), null,
246                null, null, false, CachingStrategy.newDefaultStrategy());
247
248        final byte[] buf = new byte[amtToRead];
249        int readOffset = 0;
250        int retries = 2;
251        while ( amtToRead > 0 ) {
252          int numRead = amtToRead;
253          try {
254            blockReader.readFully(buf, readOffset, amtToRead);
255          }
256          catch (IOException e) {
257            retries--;
258            if (retries == 0)
259              throw new IOException("Could not read data from datanode");
260            continue;
261          }
262          amtToRead -= numRead;
263          readOffset += numRead;
264        }
265        blockReader.close();
266        out.print(HtmlQuoting.quoteHtmlChars(new String(buf, Charsets.UTF_8)));
267      }
268
269      public static void addTableHeader(JspWriter out) throws IOException {
270        out.print("<table border=\"1\""+
271                  " cellpadding=\"2\" cellspacing=\"2\">");
272        out.print("<tbody>");
273      }
274      public static void addTableRow(JspWriter out, String[] columns) throws IOException {
275        out.print("<tr>");
276        for (int i = 0; i < columns.length; i++) {
277          out.print("<td style=\"vertical-align: top;\"><B>"+columns[i]+"</B><br></td>");
278        }
279        out.print("</tr>");
280      }
281      public static void addTableRow(JspWriter out, String[] columns, int row) throws IOException {
282        out.print("<tr>");
283
284        for (int i = 0; i < columns.length; i++) {
285          if (row/2*2 == row) {//even
286            out.print("<td style=\"vertical-align: top;background-color:LightGrey;\"><B>"+columns[i]+"</B><br></td>");
287          } else {
288            out.print("<td style=\"vertical-align: top;background-color:LightBlue;\"><B>"+columns[i]+"</B><br></td>");
289
290          }
291        }
292        out.print("</tr>");
293      }
294      public static void addTableFooter(JspWriter out) throws IOException {
295        out.print("</tbody></table>");
296      }
297
298      public static void sortNodeList(final List<DatanodeDescriptor> nodes,
299                               String field, String order) {
300
301        class NodeComapare implements Comparator<DatanodeDescriptor> {
302          static final int
303            FIELD_NAME              = 1,
304            FIELD_LAST_CONTACT      = 2,
305            FIELD_BLOCKS            = 3,
306            FIELD_CAPACITY          = 4,
307            FIELD_USED              = 5,
308            FIELD_PERCENT_USED      = 6,
309            FIELD_NONDFS_USED       = 7,
310            FIELD_REMAINING         = 8,
311            FIELD_PERCENT_REMAINING = 9,
312            FIELD_ADMIN_STATE       = 10,
313            FIELD_DECOMMISSIONED    = 11,
314            SORT_ORDER_ASC          = 1,
315            SORT_ORDER_DSC          = 2;
316
317          int sortField = FIELD_NAME;
318          int sortOrder = SORT_ORDER_ASC;
319
320          public NodeComapare(String field, String order) {
321            if (field.equals("lastcontact")) {
322              sortField = FIELD_LAST_CONTACT;
323            } else if (field.equals("capacity")) {
324              sortField = FIELD_CAPACITY;
325            } else if (field.equals("used")) {
326              sortField = FIELD_USED;
327            } else if (field.equals("nondfsused")) {
328              sortField = FIELD_NONDFS_USED;
329            } else if (field.equals("remaining")) {
330              sortField = FIELD_REMAINING;
331            } else if (field.equals("pcused")) {
332              sortField = FIELD_PERCENT_USED;
333            } else if (field.equals("pcremaining")) {
334              sortField = FIELD_PERCENT_REMAINING;
335            } else if (field.equals("blocks")) {
336              sortField = FIELD_BLOCKS;
337            } else if (field.equals("adminstate")) {
338              sortField = FIELD_ADMIN_STATE;
339            } else if (field.equals("decommissioned")) {
340              sortField = FIELD_DECOMMISSIONED;
341            } else {
342              sortField = FIELD_NAME;
343            }
344
345            if (order.equals("DSC")) {
346              sortOrder = SORT_ORDER_DSC;
347            } else {
348              sortOrder = SORT_ORDER_ASC;
349            }
350          }
351
352          @Override
353          public int compare(DatanodeDescriptor d1,
354                             DatanodeDescriptor d2) {
355            int ret = 0;
356            switch (sortField) {
357            case FIELD_LAST_CONTACT:
358              ret = (int) (d2.getLastUpdate() - d1.getLastUpdate());
359              break;
360            case FIELD_CAPACITY:
361              long  dlong = d1.getCapacity() - d2.getCapacity();
362              ret = (dlong < 0) ? -1 : ((dlong > 0) ? 1 : 0);
363              break;
364            case FIELD_USED:
365              dlong = d1.getDfsUsed() - d2.getDfsUsed();
366              ret = (dlong < 0) ? -1 : ((dlong > 0) ? 1 : 0);
367              break;
368            case FIELD_NONDFS_USED:
369              dlong = d1.getNonDfsUsed() - d2.getNonDfsUsed();
370              ret = (dlong < 0) ? -1 : ((dlong > 0) ? 1 : 0);
371              break;
372            case FIELD_REMAINING:
373              dlong = d1.getRemaining() - d2.getRemaining();
374              ret = (dlong < 0) ? -1 : ((dlong > 0) ? 1 : 0);
375              break;
376            case FIELD_PERCENT_USED:
377              double ddbl =((d1.getDfsUsedPercent())-
378                            (d2.getDfsUsedPercent()));
379              ret = (ddbl < 0) ? -1 : ((ddbl > 0) ? 1 : 0);
380              break;
381            case FIELD_PERCENT_REMAINING:
382              ddbl =((d1.getRemainingPercent())-
383                     (d2.getRemainingPercent()));
384              ret = (ddbl < 0) ? -1 : ((ddbl > 0) ? 1 : 0);
385              break;
386            case FIELD_BLOCKS:
387              ret = d1.numBlocks() - d2.numBlocks();
388              break;
389            case FIELD_ADMIN_STATE:
390              ret = d1.getAdminState().toString().compareTo(
391                  d2.getAdminState().toString());
392              break;
393            case FIELD_DECOMMISSIONED:
394              ret = DFSUtil.DECOM_COMPARATOR.compare(d1, d2);
395              break;
396            case FIELD_NAME:
397              ret = d1.getHostName().compareTo(d2.getHostName());
398              break;
399            default:
400              throw new IllegalArgumentException("Invalid sortField");
401            }
402            return (sortOrder == SORT_ORDER_DSC) ? -ret : ret;
403          }
404        }
405
406        Collections.sort(nodes, new NodeComapare(field, order));
407      }
408
409      public static void printPathWithLinks(String dir, JspWriter out,
410                                            int namenodeInfoPort,
411                                            String tokenString,
412                                            String nnAddress
413                                            ) throws IOException {
414        try {
415          String[] parts = dir.split(Path.SEPARATOR);
416          StringBuilder tempPath = new StringBuilder(dir.length());
417          out.print("<a href=\"browseDirectory.jsp" + "?dir="+ Path.SEPARATOR
418              + "&namenodeInfoPort=" + namenodeInfoPort
419              + getDelegationTokenUrlParam(tokenString)
420              + getUrlParam(NAMENODE_ADDRESS, nnAddress) + "\">" + Path.SEPARATOR
421              + "</a>");
422          tempPath.append(Path.SEPARATOR);
423          for (int i = 0; i < parts.length-1; i++) {
424            if (!parts[i].equals("")) {
425              tempPath.append(parts[i]);
426              out.print("<a href=\"browseDirectory.jsp" + "?dir="
427                  + HtmlQuoting.quoteHtmlChars(tempPath.toString()) + "&namenodeInfoPort=" + namenodeInfoPort
428                  + getDelegationTokenUrlParam(tokenString)
429                  + getUrlParam(NAMENODE_ADDRESS, nnAddress));
430              out.print("\">" + HtmlQuoting.quoteHtmlChars(parts[i]) + "</a>" + Path.SEPARATOR);
431              tempPath.append(Path.SEPARATOR);
432            }
433          }
434          if(parts.length > 0) {
435            out.print(HtmlQuoting.quoteHtmlChars(parts[parts.length-1]));
436          }
437        }
438        catch (UnsupportedEncodingException ex) {
439          ex.printStackTrace();
440        }
441      }
442
443      public static void printGotoForm(JspWriter out,
444                                       int namenodeInfoPort,
445                                       String tokenString,
446                                       String file,
447                                       String nnAddress) throws IOException {
448        out.print("<form action=\"browseDirectory.jsp\" method=\"get\" name=\"goto\">");
449        out.print("Goto : ");
450        out.print("<input name=\"dir\" type=\"text\" width=\"50\" id=\"dir\" value=\""+ HtmlQuoting.quoteHtmlChars(file)+"\"/>");
451        out.print("<input name=\"go\" type=\"submit\" value=\"go\"/>");
452        out.print("<input name=\"namenodeInfoPort\" type=\"hidden\" "
453            + "value=\"" + namenodeInfoPort  + "\"/>");
454        if (UserGroupInformation.isSecurityEnabled()) {
455          out.print("<input name=\"" + DELEGATION_PARAMETER_NAME
456              + "\" type=\"hidden\" value=\"" + tokenString + "\"/>");
457        }
458        out.print("<input name=\""+ NAMENODE_ADDRESS +"\" type=\"hidden\" "
459            + "value=\"" + nnAddress  + "\"/>");
460        out.print("</form>");
461      }
462
463      public static void createTitle(JspWriter out,
464                                     HttpServletRequest req,
465                                     String  file) throws IOException{
466        if(file == null) file = "";
467        int start = Math.max(0,file.length() - 100);
468        if(start != 0)
469          file = "..." + file.substring(start, file.length());
470        out.print("<title>HDFS:" + file + "</title>");
471      }
472
473      /** Convert a String to chunk-size-to-view. */
474      public static int string2ChunkSizeToView(String s, int defaultValue) {
475        int n = s == null? 0: Integer.parseInt(s);
476        return n > 0? n: defaultValue;
477      }
478
479      /** Return a table containing version information. */
480      public static String getVersionTable() {
481        return "<div class='dfstable'><table>"
482            + "\n  <tr><td class='col1'>Version:</td><td>" + VersionInfo.getVersion() + ", " + VersionInfo.getRevision() + "</td></tr>"
483            + "\n  <tr><td class='col1'>Compiled:</td><td>" + VersionInfo.getDate() + " by " + VersionInfo.getUser() + " from " + VersionInfo.getBranch() + "</td></tr>"
484            + "\n</table></div>";
485      }
486
487      /**
488       * Validate filename.
489       * @return null if the filename is invalid.
490       *         Otherwise, return the validated filename.
491       */
492      public static String validatePath(String p) {
493        return p == null || p.length() == 0?
494            null: new Path(p).toUri().getPath();
495      }
496
497      /**
498       * Validate a long value.
499       * @return null if the value is invalid.
500       *         Otherwise, return the validated Long object.
501       */
502      public static Long validateLong(String value) {
503        return value == null? null: Long.parseLong(value);
504      }
505
506      /**
507       * Validate a URL.
508       * @return null if the value is invalid.
509       *         Otherwise, return the validated URL String.
510       */
511      public static String validateURL(String value) {
512        try {
513          return URLEncoder.encode(new URL(value).toString(), "UTF-8");
514        } catch (IOException e) {
515          return null;
516        }
517      }
518
519      /**
520       * If security is turned off, what is the default web user?
521       * @param conf the configuration to look in
522       * @return the remote user that was configuration
523       */
524      public static UserGroupInformation getDefaultWebUser(Configuration conf
525                                                           ) throws IOException {
526        return UserGroupInformation.createRemoteUser(getDefaultWebUserName(conf));
527      }
528
529      private static String getDefaultWebUserName(Configuration conf
530          ) throws IOException {
531        String user = conf.get(
532            HADOOP_HTTP_STATIC_USER, DEFAULT_HADOOP_HTTP_STATIC_USER);
533        if (user == null || user.length() == 0) {
534          throw new IOException("Cannot determine UGI from request or conf");
535        }
536        return user;
537      }
538
539      private static InetSocketAddress getNNServiceAddress(ServletContext context,
540          HttpServletRequest request) {
541        String namenodeAddressInUrl = request.getParameter(NAMENODE_ADDRESS);
542        InetSocketAddress namenodeAddress = null;
543        if (namenodeAddressInUrl != null) {
544          namenodeAddress = NetUtils.createSocketAddr(namenodeAddressInUrl);
545        } else if (context != null) {
546          namenodeAddress = NameNodeHttpServer.getNameNodeAddressFromContext(
547              context);
548        }
549        if (namenodeAddress != null) {
550          return namenodeAddress;
551        }
552        return null;
553      }
554
555      /** Same as getUGI(null, request, conf). */
556      public static UserGroupInformation getUGI(HttpServletRequest request,
557          Configuration conf) throws IOException {
558        return getUGI(null, request, conf);
559      }
560
561      /** Same as getUGI(context, request, conf, KERBEROS_SSL, true). */
562      public static UserGroupInformation getUGI(ServletContext context,
563          HttpServletRequest request, Configuration conf) throws IOException {
564        return getUGI(context, request, conf, AuthenticationMethod.KERBEROS_SSL, true);
565      }
566
567      /**
568       * Get {@link UserGroupInformation} and possibly the delegation token out of
569       * the request.
570       * @param context the ServletContext that is serving this request.
571       * @param request the http request
572       * @param conf configuration
573       * @param secureAuthMethod the AuthenticationMethod used in secure mode.
574       * @param tryUgiParameter Should it try the ugi parameter?
575       * @return a new user from the request
576       * @throws AccessControlException if the request has no token
577       */
578      public static UserGroupInformation getUGI(ServletContext context,
579          HttpServletRequest request, Configuration conf,
580          final AuthenticationMethod secureAuthMethod,
581          final boolean tryUgiParameter) throws IOException {
582        UserGroupInformation ugi = null;
583        final String usernameFromQuery = getUsernameFromQuery(request, tryUgiParameter);
584        final String doAsUserFromQuery = request.getParameter(DoAsParam.NAME);
585        final String remoteUser;
586
587        if (UserGroupInformation.isSecurityEnabled()) {
588          remoteUser = request.getRemoteUser();
589          final String tokenString = request.getParameter(DELEGATION_PARAMETER_NAME);
590          if (tokenString != null) {
591            // Token-based connections need only verify the effective user, and
592            // disallow proxying to different user.  Proxy authorization checks
593            // are not required since the checks apply to issuing a token.
594            ugi = getTokenUGI(context, request, tokenString, conf);
595            checkUsername(ugi.getShortUserName(), usernameFromQuery);
596            checkUsername(ugi.getShortUserName(), doAsUserFromQuery);
597          } else if (remoteUser == null) {
598            throw new IOException(
599                "Security enabled but user not authenticated by filter");
600          }
601        } else {
602          // Security's not on, pull from url or use default web user
603          remoteUser = (usernameFromQuery == null)
604              ? getDefaultWebUserName(conf) // not specified in request
605              : usernameFromQuery;
606        }
607
608        if (ugi == null) { // security is off, or there's no token
609          ugi = UserGroupInformation.createRemoteUser(remoteUser);
610          checkUsername(ugi.getShortUserName(), usernameFromQuery);
611          if (UserGroupInformation.isSecurityEnabled()) {
612            // This is not necessarily true, could have been auth'ed by user-facing
613            // filter
614            ugi.setAuthenticationMethod(secureAuthMethod);
615          }
616          if (doAsUserFromQuery != null) {
617            // create and attempt to authorize a proxy user
618            ugi = UserGroupInformation.createProxyUser(doAsUserFromQuery, ugi);
619            ProxyUsers.authorize(ugi, request.getRemoteAddr(), conf);
620          }
621        }
622
623        if(LOG.isDebugEnabled())
624          LOG.debug("getUGI is returning: " + ugi.getShortUserName());
625        return ugi;
626      }
627
628      private static UserGroupInformation getTokenUGI(ServletContext context,
629                                                      HttpServletRequest request,
630                                                      String tokenString,
631                                                      Configuration conf)
632                                                          throws IOException {
633        final Token<DelegationTokenIdentifier> token =
634            new Token<DelegationTokenIdentifier>();
635        token.decodeFromUrlString(tokenString);
636        InetSocketAddress serviceAddress = getNNServiceAddress(context, request);
637        if (serviceAddress != null) {
638          SecurityUtil.setTokenService(token, serviceAddress);
639          token.setKind(DelegationTokenIdentifier.HDFS_DELEGATION_KIND);
640        }
641
642        ByteArrayInputStream buf =
643            new ByteArrayInputStream(token.getIdentifier());
644        DataInputStream in = new DataInputStream(buf);
645        DelegationTokenIdentifier id = new DelegationTokenIdentifier();
646        id.readFields(in);
647        if (context != null) {
648          final NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
649          if (nn != null) {
650            // Verify the token.
651            nn.getNamesystem().verifyToken(id, token.getPassword());
652          }
653        }
654        UserGroupInformation ugi = id.getUser();
655        ugi.addToken(token);
656        return ugi;
657      }
658
659      /**
660       * Expected user name should be a short name.
661       */
662      private static void checkUsername(final String expected, final String name
663          ) throws IOException {
664        if (expected == null && name != null) {
665          throw new IOException("Usernames not matched: expecting null but name="
666              + name);
667        }
668        if (name == null) { //name is optional, null is okay
669          return;
670        }
671        KerberosName u = new KerberosName(name);
672        String shortName = u.getShortName();
673        if (!shortName.equals(expected)) {
674          throw new IOException("Usernames not matched: name=" + shortName
675              + " != expected=" + expected);
676        }
677      }
678
679      private static String getUsernameFromQuery(final HttpServletRequest request,
680          final boolean tryUgiParameter) {
681        String username = request.getParameter(UserParam.NAME);
682        if (username == null && tryUgiParameter) {
683          //try ugi parameter
684          final String ugiStr = request.getParameter("ugi");
685          if (ugiStr != null) {
686            username = ugiStr.split(",")[0];
687          }
688        }
689        return username;
690      }
691
692      /**
693       * Returns the url parameter for the given token string.
694       * @param tokenString
695       * @return url parameter
696       */
697      public static String getDelegationTokenUrlParam(String tokenString) {
698        if (tokenString == null ) {
699          return "";
700        }
701        if (UserGroupInformation.isSecurityEnabled()) {
702          return SET_DELEGATION + tokenString;
703        } else {
704          return "";
705        }
706      }
707
708      /**
709       * Returns the url parameter for the given string, prefixed with
710       * paramSeparator.
711       *
712       * @param name parameter name
713       * @param val parameter value
714       * @param paramSeparator URL parameter prefix, i.e. either '?' or '&'
715       * @return url parameter
716       */
717      public static String getUrlParam(String name, String val, String paramSeparator) {
718        return val == null ? "" : paramSeparator + name + "=" + val;
719      }
720
721      /**
722       * Returns the url parameter for the given string, prefixed with '?' if
723       * firstParam is true, prefixed with '&' if firstParam is false.
724       *
725       * @param name parameter name
726       * @param val parameter value
727       * @param firstParam true if this is the first parameter in the list, false otherwise
728       * @return url parameter
729       */
730      public static String getUrlParam(String name, String val, boolean firstParam) {
731        return getUrlParam(name, val, firstParam ? "?" : "&");
732      }
733
734      /**
735       * Returns the url parameter for the given string, prefixed with '&'.
736       *
737       * @param name parameter name
738       * @param val parameter value
739       * @return url parameter
740       */
741      public static String getUrlParam(String name, String val) {
742        return getUrlParam(name, val, false);
743      }
744    }


text:
Q: createWriteStream in node seems to execute 'end' event before 'data' I am unable to understand how the event loop is processing my snippet. What I am trying to achieve is

*

*to read from a csv

*download a resource found in the csv

*upload it to s3

*write it into a new csv file

const readAndUpload =  () => {
    fs.createReadStream('filename.csv')
    .pipe(csv())
    .on('data', ((row: any) => {
        const file = fs.createWriteStream("file.jpg");
        var url = new URL(row.imageURL)
        // choose whether to make an http or https request
        let client = (url.protocol=="https:") ? https : http
        const request = client.get(row.imageURL, function(response:any) {
            // file save
            response.pipe(file);
            console.log('file saved')
            let filePath = "file.jpg";
            let params = {
                Bucket: 'bucket-name',
                Body : fs.createReadStream(filePath),
                Key : "filename.jpg"
            };
            // upload to s3
            s3.upload(params, function (err: any, data: any) {
                //handle error
                if (err) {
                  console.log("Error", err);
                }

                //success
                if (data) {
                  console.log("Uploaded in:", data.Location);
                  row.imageURL = data.Location
                  writeData.push(row)
                //   console.log(writeData)
                }
              });
        });
    }))
    .on('end', () => {
        console.log("done reading")
        const csvWriter = createCsvWriter({
            path: 'out.csv',
            header: [
                {id: 'id', title: 'some title'}
            ]
        });
        csvWriter
            .writeRecords(writeData)
            .then(() => console.log("The CSV file was written successfully"))
    })
}

Going by the log statements that I have added, done reading and The CSV file was written successfully is printed by before file saved. My understanding was that the end event is called after the data event, so I am unsure of where I am going wrong.
Thank you for reading!

A: I'm not sure if this is part of the problem or not, but you've got an extra set of parens in this part of the code.  Change this:
.on('data', ((row: any) => {
     .....
})).on('end', () => {

to this:
.on('data', (row: any) => {
     .....
}).on('end', () => {

And, if the event handlers are set up properly, your .on('data', ...) event handler gets called before the .on('end', ....) for the same stream.  If you put this:
console.log('at start of data event handler');

as the first line in that event handler, you will see it get called first.
But, your data event handler uses multiple asynchronous calls and nothing you have in your code makes the end event wait for all your processing to be done in the data event handler.  So, since that processing takes awhile, it's natural that the end event would occur before you're done running all that asynchronous code on the data event.

In addition, if you ever can have more than one data event (which one normally would), you're going to have multiple data events in flight at the same time and since you're using a fixed filename, they will probably be overwriting each other.

The usual way to solve something like this is to to stream.pause() to pause the readstream at the start of the data event processing and then when all your asynchronous stuff is done, you can then stream.resume() to let it start going again.
You will need to get the right stream in order to pause and resume.  You could do something like this:
let stream = fs.createReadStream('filename.csv')
 .pipe(csv());

stream.on('data', ((row: any) => {
   stream.pause();
   ....
});

Then, way inside your s3.upload() callback, you can call stream.resume().  You will also need much, much better error handling that you have or things will just get stuck if you get an error.
It also looks like you have other concurrency issues too where you call:
response.pipe(file);

And you then attempt to use the file without actually waiting for that .pipe() operation to be done (which is also asynchronous).  Overall, this whole logic really needs a major cleanup.  I don't understand what exactly you're trying to do in all the different steps to know how to write a totally clean and simpler version.

redpajama_set_name: RedPajamaStackExchange


text:
History of the study
Management and funding
CNC on social media
COVID-19 Survey
Age 17 Survey
Age 7 Survey
Age 9 Months Survey
Happiness and aspirations
Child of the New Century (CNC) has followed you through primary school and will continue to gather information about your lives in secondary school. Researchers have used CNC to learn more about a wide range of issues relating to school life, including achievement and bullying.
CNC has shown that parents considered several factors when choosing a school for their child. Most parents wanted their children to go to primary schools with good academic results that were not too far from home. Many parents also preferred schools that weren't religious. At age 11, nearly 4 in 10 children attended mixed-sex and non-religious state schools.
When it came to secondary school choices, lots of young people were starting to make their own decisions about their future. One in three families said the most important factor was that their child liked the school. The school's exam results were also a key consideration for many parents.
School achievement
Studies based on CNC have revealed that lots of things can affect how you do in school.
For instance, researchers have found that the month you were born could influence which classes or sets you are in. Their findings showed that children born in the summer months were in general more likely to be placed in lower sets because they were almost a year younger than their classmates born in September – but there are of course many other factors that determine which sets you are in too.
Research has also found that factors such as your family background, parents' education, parents' jobs, and whether you are a boy or a girl are closely related to how well you do in school.
In the age 7 survey, you were asked whether you were bullied at school. Researchers found that primary school pupils with special educational needs were twice as likely as other children to be bullied a lot. Overall, more than 1 in 10 children with special needs said they were always bullied by other pupils, compared to just over 1 in 20 of their classmates.
The researchers also found that children with a long-term illness or impairment that limited their day-to-day activity, such as type 1 diabetes, asthma or partial sight, were slightly more likely to be bullied than other children.
CHECK THE SOURCES
What Parents Want: School preferences and school choice (2009) by Simon Burgess, Ellen Greaves, Anna Vignoles and Deborah Wilson
In-school ability grouping and the month of birth effect: Preliminary evidence from the Millennium Cohort Study (2013) by Tammy Campbell
Ethnicity and gender gaps in early childhood (2013) by Kirstine Hansen and Elizabeth Jones
Prevalence of streaming in UK primary schools: evidence from the Millennium Cohort Study (2013) by Sue Hallam and Sam Parsons
Poverty, Family Resources and Children's Early Educational Attainment: The Mediating Role of Parenting (2011) by Kathleen Kiernan and Fiona Mensah
Bullying experiences among disabled children and young people in England: Evidence from two longitudinal studies (2014) by Stella Chatzitheochari, Sam Parsons and Lucinda Platt
Child of the New Century
FREEPOST RTKC-KLUU-RSBH
20 Bedford Way
London WC1H 0AL
Email: childnc@ucl.ac.uk

redpajama_set_name: RedPajamaCommonCrawl


text:
require "spec_helper"

describe Mongoid::Relations::Cascading do

  describe ".cascade" do

    let(:klass) do
      Class.new.tap { |c| c.send(:include, Mongoid::Document) }
    end

    context "when a dependent option is provided" do

      let(:metadata) do
        Mongoid::Relations::Metadata.new(
          :name => :posts,
          :dependent => :destroy,
          :relation => Mongoid::Relations::Referenced::Many
        )
      end

      let!(:cascaded) do
        klass.cascade(metadata)
      end

      it "adds the action to the cascades" do
        klass.cascades.should include("posts")
      end

      it "returns self" do
        cascaded.should == klass
      end
    end

    context "when no dependent option is provided" do

      let(:metadata) do
        Mongoid::Relations::Metadata.new(
          :name => :posts,
          :relation => Mongoid::Relations::Referenced::Many
        )
      end

      let!(:cascaded) do
        klass.cascade(metadata)
      end

      it "does not add an action to the cascades" do
        klass.cascades.should_not include("posts")
      end

      it "returns self" do
        cascaded.should == klass
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


These African beaded fetish dolls or Namji dolls, are gifted to young females of the tribe as a fertility doll to teach them the responsibilities of motherhood. Please select the arrows, inserted on either side of the above image, to see more options.
Materials: Carved from solid wood, multicolored trade glass beads, cowrie shells, coins, brass amulets, fibers, and leather strips.
Available Colours: White, Black, Red, Blue (light and dark) Green, Yellow, Orange, to name just a few.


text:
Call us now 020 3633 2195
Matrimonial Investigations
Legal/Solicitor Enquiries
Expert Private Detective in Fulham
25 Years Experience With Male & Female Private Detective Available
Private investigators and private detectives are normally putting their lives on the line when conducting an investigation; this is why it really is imperative for them to take all precautionary measures in order to make certain their safety while conducting the investigation. It is however also essential that they're able to obtain only probably the most accurate information from their topic of investigation, as a result in circumstances exactly where endangering one's life is at part and parcel with gathering evidence the private investigator or private detective can resort to extra ordinary measures. One such extra ordinary measure would be to utilise investigation or "spy" gadgets. The use of these kinds of gadgets would aid make certain the safety of the private investigator and private detective as the gadgets would enable them to collect data from a distance.
The GSM Spy telephone is one such device that will be utilised by private investigators and private detectives in gathering accurate details. The device is an actual GSM telephone which may be integrated with the software. The defining function of this item is actually the software program which is integrated with all the GSM telephone. The software is undetectable from the mobile phone. It has a function that if the phone is switched on will alert you by way of SMS when a phone call is produced along with the number of the party becoming referred to as is also sent by means of SMS and it is going to also send you a copy of the SMS message sent via the GSM telephone. Via dialling a pre-defined number you may also have the ability to intercept and hear telephone conversations. An additional excellent feature of this software is that you could use the telephone to record room conversations by just sending a text message command. Lastly, even should you be not monitoring the phone you can truly direct the software to record all telephone conversations.
With this device and software program private investigators and private detectives can gather the required and most accurate data.
http://www.privatedetective-gateshead.co.uk
FREE Professional Expert Advice Call 020 3633 2195
Our Private Detective Services
Listening Device
Nanny Monitoring
Privacy and Cookie Policy | Terms of Use | Private Investigators | About us | Terms & Conditions | Contact us | Articles |


text:
@class DBPAPERAddMember;
@class DBPAPERPaperDocPermissionLevel;
@class DBSHARINGMemberSelector;

#pragma mark - API Object

///
/// The `AddMember` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBPAPERAddMember : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// Permission for the user.
@property (nonatomic, readonly) DBPAPERPaperDocPermissionLevel * _Nonnull permissionLevel;

/// User which should be added to the Paper doc. Specify only email or Dropbox
/// account id.
@property (nonatomic, readonly) DBSHARINGMemberSelector * _Nonnull member;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param member User which should be added to the Paper doc. Specify only
/// email or Dropbox account id.
/// @param permissionLevel Permission for the user.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithMember:(DBSHARINGMemberSelector * _Nonnull)member
                       permissionLevel:(DBPAPERPaperDocPermissionLevel * _Nullable)permissionLevel;

///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
/// @param member User which should be added to the Paper doc. Specify only
/// email or Dropbox account id.
///
/// @return An initialized instance.
///
- (nonnull instancetype)initWithMember:(DBSHARINGMemberSelector * _Nonnull)member;

- (nonnull instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `AddMember` struct.
///
@interface DBPAPERAddMemberSerializer : NSObject

///
/// Serializes `DBPAPERAddMember` instances.
///
/// @param instance An instance of the `DBPAPERAddMember` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBPAPERAddMember` API object.
///
+ (NSDictionary * _Nonnull)serialize:(DBPAPERAddMember * _Nonnull)instance;

///
/// Deserializes `DBPAPERAddMember` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBPAPERAddMember` API object.
///
/// @return An instantiation of the `DBPAPERAddMember` object.
///
+ (DBPAPERAddMember * _Nonnull)deserialize:(NSDictionary * _Nonnull)dict;

@end


Remember what happened four days ago?
Read it here if you don't.
Four days ago, it was still alive and trapped among my forested kah moh but now, it 翘辫子 already.
I wonder why all kar chuaks have to flip over everytime they die?
This entry was posted in Uncategorized and tagged cockroach, dead, dead cockroach, roach.
This was the Sichuan Earthquake which strike on 12th of May leaving at least 20,000 people dead.
Photos shown above are taken from here.
Myanmar, on the other hand was hit by Cyclone Nagis on 3rd of May. The death toll estimated by the UN stands at 100,000, with 1/3 of them being children.
Mother Nature is very sick and she is sending out the signals already.
Must we wait till we've lost everything before we start to realize the seriousness of this matter?
This entry was posted in Uncategorized and tagged casualty, china, cyclone, dead, disaster, earthquake, myanmar, nagis, natural, sichuan.
I was on the bus when I saw this accident near my home. A motorbike was lying on its side on the road beside a bus and there was a body next to it, covered with plastic.
When I read about this accident in the newspapers, this poor biker has fallen off from his bike and had his head ran over by the SBS bus.
This reminded me of the fatal accident involving my friend's sister in the States. Actually, this accident happened many years ago and at that time, it was even on the headlines of the newspapers. Recently, this news was in the headlines again.
My friend's sister aspired to be an Astrologist, but there wasn't any local Uni here offering the course so off she went to the States to pursue her dream to study about the stars and the planets.
On that fateful day, the boyfriend was driving her back to the hostel but somehow, their vehicle crashed into a truck. The boyfriend escaped with minor injuries but my friend's sister wasn't so lucky. Her skull was caved in and she died instantly on the spot.
The boyfriend felt so remorseful that he committed suicide. His friends had found him lying in a pool of blood when they broke into his apartment. He had slit his wrist.
Such a terrible ending (and dramatic too) to two young lives. The wake was held at the Singapore Casket but I didn't attend the funeral. Its not that I didn't want to attend but I have always had a phobia of attending such depressing events. They reminded me of death and sorrow and I would feel very heartbreaking by it. The scene would just keep replaying itself over and over again in my mind it would take me a very long time to get over it!
I heard that her head was puffed up with cotton wool to make it look fuller. I felt so sorry for my friend's family, especially his mother. She was crying her heart out over the tragic death of her daughter. It must be a very painful moment for the family when they bury her.
I guess life would never be the same for their family now, especially during her birthdays and death anniversary. They would post her obituary in the newspapers without fail during her death anniversary and they would hold a memorial service for her.
Life is so unpredictable and fragile so treasure your loved ones around you. You never know when fate might decide to play a joke on you and took your loved one away from you.
This entry was posted in Uncategorized and tagged accident, dead, love.


Drinking just one glass of fresh whey, you can strengthen your immune system. Then no cold you will not be able to overcome. Infectious diseases remain in the past, and with them the virus.
The digestive system, thanks to this product, too, is restored. Healing of the stomach lining and intestinal flora back to normal, to use the serum a couple of weeks. This product cures gastritis and colitis. Useful and suffering from constipation.
Whey is able to restore water and salt balance. Because the components in it of excess fluid, which contributes to the disappearance of swelling. The body is cleared of toxins, toxins. It is enough to drink a glass of whey, fulfilling one condition – you drink it on an empty stomach.
It is recommended to enter into the diet this healthful beverage "cores" and "high blood pressure". Substances which are rich in serum, cleanse the body of bad cholesterol, which means that the vessels will not produce dangerous "plaques" that clog them.
The product shown in this depressive state. It turns out that whey contains components that have a negative effect on the production of so-called stress hormones. And the production of happy hormone serotonin, on the contrary, promotes.
Successfully you can use whey for weight normalization. Because it can reduce the appetite. A rich set of nutrients can help without harm to the body, to stick to a reducing weight diet.
Serum and has an excellent whitening effect, especially when you have oily skin or normal. If you add a few drops of lemon juice and wipe the skin with this mixture every day, the impact will increase.
Will help milk whey and a sun-burnt skin. For this we need to add in warm bath, a couple of liters of serum and lay there for about twenty minutes.
This healing tool you can also restore hair, if you wash them with a mixture of dairy whey and a decoction of burdock roots once a week.
The only reason to refuse to accept the serum — individual intolerance to lactose. A person with such a problem may be an allergic reaction, swelling, diarrhea, severe flatulence.
Another danger is improper storage. Missing natural product — environment for development of pathogenic bacteria.
Despite contraindications, the whey is very healthy and tasty beverage which can be applied in dozens of ways. Be sure to include it in your diet!


If you're looking for a good memory foam body pillow to keep your body ensconced in relaxing comfort, then the Original Shredded Memory Foam Body Pillow Review with Viscose Rayon Cover derived from Bamboo, is the answer to your needs. This US-made body pillow from Coop Home Goods is a full body memory foam pillow designed to create an ideal environment for you which is conducive to perfect sleep and rest. Summer or winter, hot or cold weather, you'll find this body pillow ideal for all your comfort and sleep needs. So if you want to simply rest your aching back and shoulders, and possibly your legs and arms too, just go for this body pillow. And if you want a good night's restful sleep, then again, this is the one for you. Its customizable design and construction make this shredded memory foam body pillow a perfect fit for all your needs.
The range of features of this Coop Home Goods memory foam body pillow will leave you more than amazed. It will actually inspire you to work better and remain energized all day, by helping you sleep well through the night, or maybe just rest your aching body through the day. With this memory foam pillow hugging your tired body, you'll really need nothing more to get some much-needed peace and comfort, as well as relief from aches and pressure.
The CeriPUR-US certified foam used to make this body pillow has no ozone depleters, PBDEs, TDCPP, mercury, lead, formaldehyde, phthalates regulated by the CPSC, CFCs, TCEP flame retardants—in short, it has nothing that can harm your body in any way—a fact tested and endorsed by independent accredited testing laboratories.
This memory foam body pillow is not only dust mite resistant but also hypoallergenic, which means total safety for those prone to allergies, and also for pregnant women.
You can easily machine wash the whole pillow, thanks to the 40% viscose rayon fabric used in the pillow case. The viscose rayon comes from bamboo. The remaining 60% is polyester, thereby ensuring excellent support for sleeping, especially while sleeping on your side.
By helping regulate your body temperature, this body pillow keeps you comfortably cool day after day, night after night, irrespective of the temperatures outside.
This body pillow comes with a 5-year warranty, so you need not worry about find a frequent replacement. One thing it's not going to do is leave you in the lurch. It's well made and crafted for long-lasting comfort.
The excellent benefits of this memory foam body pillow notwithstanding, you're likely to come across certain negatives which you may like to analyze before taking the final decision on its purchase.
Unlike a normal memory foam body pillow, which tends to build up heat as a result of poor air circulation, the shredded memory foam pillow is designed to keep you cool and relaxed, with its breathable fabric to maintain air flow. And it does so without compromising on the support provided by a regular memory flow body pillow. Interestingly, even as it adapts itself to suit your body position, it doesn't go out of shape and provides the shapeability of a down pillow.
You can use this body pillow to sleep or simply as a prop to support your back while you watch television or read a book, or perhaps simply work at your laptop trying to close some urgent assignment. Since it combines the support provided by a memory foam pillow with the softness and flexibility of a down pillow, the original shredded memory foam body pillow provides an excellent custom fit.
It's highly breathable, which means you're not going to be left struggling to breathe while sleeping in its soothing comfort. The fact that you can actually reduce the fluffiness at the top end of the pillow makes it ideal for supporting your knees, which is especially useful for a side sleeper. The bamboo cover gives an added cooling advantage to this pillow, which you're simply going to love if you want your pillow to remain well ventilated while sleeping, which is something not many other pillows in this range provide.
This is one of the best-selling body pillows on the market. It comes in with very high ratings of 4.6 out of 5 with 90% four stars or higher, and only 3% one star. This body pillow is selling for around $70 currently, and we recommend it.


text:
Edward Lechowicz (ur. 7 października 1858, zm. 7 października 1938) – polski prawnik, urzędnik w II RP.

Życiorys
Ukończył studia prawnicze. Po odzyskaniu przez Polskę niepodległości został urzędnikiem w służbie państwowej. Objął funkcję prawnika w Prezydium Rady Ministrów. W tej funkcji brał udział w rokowaniach polsko-sowieckich po wojnie polsko-bolszewickiej, a 18 marca 1921 był jednym z przedstawicieli RP, którzy podpisali traktat ryski. Pełnił funkcję dyrektora departamentu legislatywnego oraz Prezesa Najwyższej Komisji Dyscyplinarnej w Prezydium Rady Ministrów.

Pochowany na cmentarzu Powązkowskim w Warszawie (kwatera 23-6-24,25).

Ordery i odznaczenia

 Krzyż Komandorski z Gwiazdą Orderu Odrodzenia Polski (10 listopada 1928)
 Krzyż Komandorski Orderu Odrodzenia Polski (2 maja 1922)
 Złoty Krzyż Zasługi (9 listopada 1932)

Przypisy

Odznaczeni Krzyżem Komandorskim Orderu Odrodzenia Polski (II Rzeczpospolita)
Odznaczeni Krzyżem Komandorskim z Gwiazdą Orderu Odrodzenia Polski (II Rzeczpospolita)
Odznaczeni Złotym Krzyżem Zasługi (II Rzeczpospolita)
Pochowani na cmentarzu Powązkowskim w Warszawie
Polscy prawnicy
Urodzeni w 1858
Urzędnicy Prezydium Rady Ministrów II Rzeczypospolitej
Zmarli w 1938

redpajama_set_name: RedPajamaWikipedia


Many items over the years have been converted from less efficient materials to plastic for a number of reasons including: cost, efficiency and durability. Money is the latest item to make the switch. I know what you are thinking, debit cards and credit cards have been around for quite a while, but I am not talking about plastic cards. I'm talking about actual polymer banknotes, paper money being changed to plastic!
If you have recently gone to Canada or Mexico, you may already be familiarly with plastic currency. There are 20 countries so far that have switched from paper to plastic. Great Britain has plans to join the conversion in 2016. Great Britain will be rolling out 5 pound bills printed on polymer instead of paper.
There are some obvious advantages of plastic versus paper . The first advantage is that plastic lasts longer. In Great Britain, paper money, on average, lasts around 6 months. Plastic bills will last an average of 2.5 years. The durability of plastic over paper is a major advantage. The polymer banknote can survive the washing machine, rain storms and coffee spills without getting destroyed or even stained. Gone are the days of vending machines refusing your dollar bill! Other advantages to these bills lasting 4 times longer is the decrease in production costs and pollution. The polymer banknotes can even be recycled after they are worn beyond use.
While these benefits alone seem to tip the scale in favor of plastic, the real reason many countries are choosing to switch to polymer banknotes is security. The new polymer banknotes are extremely difficult to counterfeit. Canada's banknotes have added features including a transparent section of the banknote containing color-shifting historically significant graphics, metallic details and a maple leaf made out of a series of numbers. These features have successfully decreased counterfeit money in Canada. It is for this reason that the Bank of England decide to begin manufacturing polymer banknotes. Despite the obvious benefits, the United States currently has no plans to change their paper money over to polymer banknotes.


text:
Assessments & Advisory
Portfolio Assessments
Private Asset & Fund Optimization
Rob Roderick
Rob Roderick is an executive leader, operator, investor, and finance expert with 31 years of operational and transactional experience in financial services and private equity executing deals and investment strategy as well as forming and leading teams. Rob worked for 27 years in several GE entities.
Rob Roderick is an executive leader, operator, investor, and finance expert with 31 years of operational and transactional experience in financial services and private equity executing deals and investment strategy as well as forming and leading teams. Rob worked for 27 years in several GE entities: GE Equity, GE Asset Management, GE Capital, GE Audit Staff. He is a graduate of the GE Financial Management Program.
Rob has deep experience in principal investing, portfolio management, investment operations and business risk management. He has played central roles executing business growth: direct minority investing, co-investment programs, pledge funds, fund-of-funds, warrants, portfolio run-off, secondaries, portfolio acquisitions/divestitures, pension asset management, institutional sales support, client service programs.
During his tenure with GE Capital, Equity Rob was Managing Director, Portfolio and Business Risk for a $2.5 billion portfolio of diverse deals. He executed as principal investor, risk leader and member of the investment committee. In his roles he executed in several capacities: led a restructured/turnaround portfolio through the financial crisis, formed new onshore/offshore investment management teams, implemented portfolio management system, developed early warning tools, established performance and reporting systems, led quarterly risk management program, established valuation policy and investment modeling program. Rob generated substantial operating efficiencies, freed-up capacity, increased portfolio company value and enabled harvest of over $1.3B in net gains over a 10-year period.
Rob also served as Managing Director and Business Risk Leader for GE Capital Divestiture Group where he led the divestiture process for several portfolio/deal exits for 450+ investments. Since GE, he has served as a Trusted Business Advisor for a global manage services and digital transformation firm, and as an Investment Partner and Operating Leader for an independent private equity sponsor providing bespoke capital solution for small and medium sized companies.
Rob received his MBA from NYU Stern School of Business with a concentration in Finance and Marketing, and International Business co-major, and he received a Bachelor of Science degree from Bentley University in Finance.
Back to Team Members list
info@kirchnergroup.com
Copyright © 1985-2023 Kirchner Group. All rights reserved.


text:
More LA Business Journal
Valley Contractor Target of LAX Lawsuit
By Mark Madler
A Sylmar construction firm was named among the defendants in a lawsuit over alleged shoddy work done on a runway repair project at Los Angeles International Airport.
The joint venture between Tutor-Saliba Corp., in Sylmar, and O&G Industries Inc., in Torrington, Conn., was among the four defendants named in the lawsuit filed last week by the city in Los Angeles Superior Court, according to a story in the Los Angeles Times.
Tutor-Saliba is a subsidiary of Tutor Perini Corp., also based in the northeast San Fernando Valley community.
City officials told the Times the runway had many construction defects, including cracks, exposed steel reinforcing bars and deteriorating concrete since being rebuilt in 2007 at a cost of $250 million.
In the lawsuit, the city attorney's office alleged the runway "is unfit for its intended purpose and the city will incur ongoing consequential property damage and economic losses as a result of the deficiencies," according to the Times.
Shares of Tutor-Perini gained 57 cents, or about 2.5 percent, to close at $23.68 on the Nasdaq.
Tutor Perini Gains Guam Projects
Tutor Perini Prevails in Court Judgment
Tutor Perini Secures $1.4 Billion Wilshire Subway Contract
Tutor Perini Receives $190 Million Vegas Settlement
Perini Completes Tutor-Saliba Acquisition
Sylmar Contractor Sues City
Tutor Perini Lands $1.4 Billion Airport Contract
Tutor Perini Partnership Lands $1.4 Billion Airport Contract
The Book 2021 is here. To view, please click here.
The Valley 200
© 2021 San Fernando Valley Business Journal


text:
Government Policies and Schemes
A scheme for training women farmers under the Madhya Pradesh Women in Agriculture (MAPWA) Project was being implemented with the cooperation of which country?
MP Patwari Previous Paper 16 (Held On: 15 Dec 2017 Shift 2)
View all MP Patwari Papers >
Option 2 : Denmark
The correct answer is Denmark.
Madhya Pradesh Women in Agriculture(MAPWA) Project
MAPWA had started a scheme for training women farmers in 1994 with the cooperation of Denmark.
This scheme was initially started in 7 districts of Madhya Pradesh.
In 2007-08, it was implemented in all districts of Madhya Pradesh.
It provides training on how to use advanced farming tools and how to increase production with minimum cost.
Capital: Copenhagen
Currency: Danish Krone
Prime Minister: Mette Frederiksen
Country Capital Currency President Prime Minister
USA Washington D.C. US Dollar Joe Biden NA
Australia Canberra Australian Dollar NA Scott Morrison
New Zealand Wellington New Zealand Dollar NA Jacinda Arden
More Government Policies and Schemes Questions
Q1. Which department has launched the Integrated Health Information Platform Portal in Haryana ?
Q2. Haryana Government has decided to increase the old-age pension amount by how much Rupees every year?
Q3. Under which scheme hot milk, hot water and baby food will be available at railway stations ?
Q4. Akanksha Scheme is related to
Q5. Which among the following are the five principles of peaceful co-existence of Panchsheel as outlined by Jawaharlal Nehru?
Q6. Which of the following is not included in Integrated Housing and Slum Development Programme in H.P.?
Q7. When was unique ID Aadhaar Programme started in Himachal Pradesh?
Q8. World's first emissions trading system for particulate pollution has been launched by ______.
Q9. Which of the following project was launched by Khadi and Village Industries Commission (KVIC) to make carry bags by mixing processed and treated plastic waste with cotton fibre rags?
Q10. Which of the following factors are considered by Commission for 'Agricultural Costs and Prices' (CACP) while determining MSP for crops? I. Price trend in the domestic and international markets. II. Inter-crop price parity. III. Terms of trade between agricultural and non-agricultural sectors. IV. Cost of production.
Start your FREE coaching now >>
Madhya Pradesh Patwari 2021
More General Knowledge Questions
Q1. In which year Indian government has enacted the Consumer Protection Act?
Q2. In which year the United Nations adopted the UN Guidelines for Consumer Protection?
Q3. The Self Help Groups (SHGs) have been set in India with an aim to help the rural poor, especially
Q4. The activities in primary, secondary, and tertiary sectors are
Q5. When was the Human Development Report published for the first time?
Q6. Which of the following is one of the criteria of the UNDP for measuring development that is also used by the World Bank in classifying different countries?
Q7. Underemployment occurs when people:
Q8. The total income of the country divided by its total population is termed as?
Q9. Who among the following is known as Father of Economics?
Q10. Who was crowned champion of the 2021 US Open?


Kelly has had a photography business for 15 years, but recently decided to take it in a new direction. Pop Your Paws is a digital painting process. Kelly starts with a photograph that you provide. This is NOT your typical pop art! Every inch of the photo is digitally "painted" using a specialized painting tablet. All art pieces are printed on high quality, stretched and wrapped canvas. Each piece is ready to be hung. Please ask about the breeds Kelly has done and since it isn't considered "custom", can significantly lower your canvas cost. Please email for more information.
All pets are welcome! A fun and different way to see your furry friends! You take family portraits -- isn't your pet a part of your family?


text:
Category Archives: Punia International Airport
Posted on August 20, 2014 by lebonrichard under Punia International Airport
Just like Kindu, Punia's airstrip is a lifeline, albeit one accessible only to those who can pay the fares – for everyone else, goods are pushed one week through the jungle from Kisangani, on the back of heavily laden bicycles pushed by muscly young 'tolekistes'.
Over a barely passable mud ridge, Punia International Airport is a red strip hewn out of the jungle. A few flights each week alight here, shared between our own supplies of medicines, fuel and vehicle parts; and between the merchants loading cassiterite (tin ore) for the return journey. Cassiterite is the main economy in Punia – mined on the surface in large temporary camps in the forests. The camps are entirely informal, villages of bamboo and rags, populated by unemployed travellers, whose payment is per kilogram from the merchants in town, amounting to an average of less than $4 per day. From the frequency of flights going out of the two airstrips in the district, I estimate that 3,000 tons of cassiterite leave Punia annually, containing approximately 70% tin at a market price of $15-20,000 per ton, or an estimated $140,000 per day.
I sense the locals are entirely unaware of the global tin market, but there is an unfocussed sense of disgruntlement – mining is very unpopular, and Punia's residents are highly xenophobic – assuming that all foreigners, Congolese or expatriate, health workers or engineers alike, have arrived to mine and profiteer. Sometimes people throw stones at the bicycles arriving at the airstrip laden with cassiterite, and the two most recent incidents of public unrest in Punia were outside the small rooms of the mining companies, protesting abut territorial and operational rights for a site 25km out of town.
At the airport, the merchants want to use the return journeys of our medical flights to load cassiterite – on the first such occasion, they shouted, crowded and intimidated in trying to force the goods onto the plane. Practically, it made sense to use the empty planes – but I knew how hard it was to persuade locals into the health centres, and, in this context, any association with mining would spell failure for our projects.
Once the rules of the game were established, we spent many hours in the VIP lounge with the miners and local dignitaries, wiling away the unknown time waiting for a cargo – sometimes radio and telephone communications were so limited that we wouldn't know when a plane was arriving, or even at which airstrip. Once, for two consecutive days, we moved several tons of medicines and construction material to the airstrip, destined for Kasese, an even more remote outpost than Punia, only to discover that the flight had been bumped, replaced by violent thunderstorms and torrential downpours. It was some recompense to our tired eyes that the airport was an architectural monument – the VIP lounge had been designed in the same shared space as the departure lounge, arrivals hall, and passport control. This main concourse, under half the shade offered by the jungle canopy, consisted of two broken bamboo benches and a small table.
Customs turned out to be the infant reception committee who chase the plane down the runway as it takes off again. Immigration is more real, a small hut in town, containing a broken pencil guarded proudly by a character who gives expert lectures on his own self-importance, although, since we were his only immigrants, we eventually persuaded himself, and his pencil, to join the VIP lounge festivities each week.
The airstrip began to grow on me – at night, as with Kindu, it was a quiet place to run into the sunset without half the village chasing, while by day it spoke Punia's commercial and political story in its long waits, fraught encounters and lucky escapes – I had once watched as an overloaded Russian Antonov grazed the trees at the end of the runway. And even Punia's gateway to the outside world, the vortex in the jungle, seemed to want to close – once, we left the airstrip for one month without any shipments, and the vegetation was already a metre high.
I enjoyed flying even more – especially in the early morning, when the long light breaks over the horizon, and the forest beneath is taking its daily breath, exhaling gentle wisps of steam that sit below the sky. And comedy Fred, our Congolese-American bush pilot, was a local hero – he knew how to land on the road at the next base, he had been involved in several rescue operations for planes (a lamentably common occurrence, more than once down to adventurous young pilots hitting cables along the river), and he was usually surrounded by a fan club of admiring local mamas at each stop. Unlike some pilots in Congo, unwanted overspill from the Russian forces or mercenaries from South Africa, he also had a religious devotion to engine maintenance and loading regulations – Fred only ever got angry if he felt a box was inaccurately weighed or misplaced in his cargo hold.
Once, having cleared the trees at the end of the runway, I found myself alone on the twin-engine plane with Fred and his co-pilot. Fred beckoned me forward, and offered me the controls. It was like steering a ship – a delayed reaction, and even finer movements. After I felt confident keeping the plane on the level and bearing, I started to look at the instrumentation, and asked about an ominous rage of green on the radar screen. Fred made me turn towards it, and left me to control the plane as it dropped and bucked through the cloud. Relieved to regain the skyline at the other side, I was suddenly very interested in emergency procedures. I asked Fred what happens if he lost an engine. Promptly, Fred turned off one of the engines, and, with his hands calmly folded in his lap beneath the dual controls, expected me level the plane. I resolved not to ask any further questions – but, drained in body and mind as I handed over to Fred above the peaceful waters of Lake Kivu, I pondered that we might all learn a lot quicker for the bravery of such teaching methods.


Taking inspiration from the Orient Express breathtaking sense of style and luxurious way of traveling, S.T. Dupont has created limited edition product that is symbolic in representation of the Princess Dragomiroff room and the S.T. Dupont trunk case used by her in the film. The trunk case has been transformed into an exceptional lighter and writing instrument signifying the 145 years of know-how of Maison S.T. Dupont. The creations are beautifully placed in a theatrical pack showcasing the cabin of the princess.


text:
#include <SimpleGL/helpers/SimpleGLHelpers.h>
#include "sgl-test.h"

#include <vector>
#include <random>
#include <climits>
#include <algorithm>
#include <functional>
#include <chrono>
#include <thread>

//using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>;

void clearColor (sgl::Framebuffer& fbo, float r, float g, float b, float a){
    auto bg = sgl::bind_guard(fbo);
    glClearColor(r,g,b,a);
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0,0,0,1);
}

void clearColor (sgl::Framebuffer& fbo, float v){
    clearColor(fbo, v, v, v, 1.f);
}

sgl::Surface2D createSurface (int w, int h, int components) {
    GLenum fmts[4] = {GL_RED, GL_RG, GL_RGB, GL_RGBA};
    GLenum ifmts[4] = {GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F};

    sgl::Texture2D tex = sgl::TextureBuilder2D()
            .format(fmts[components-1], ifmts[components-1])
            .dataType(GL_FLOAT)
            .build(w,h);

    sgl::Surface2D surf{tex};
    clearColor(surf.fbo, 0, 0, 0, 1);
    return surf;
}

sgl::Slab2D createSlab (int w, int h, int components) {
    return {createSurface(w,h,components), createSurface(w,h,components)};
}

struct SimState {
    sgl::Framebuffer fbo;

    size_t width;
    size_t height;
    size_t gridWidth;
    size_t gridHeight;
    float timeStep;
    float cellSize;
    float splatRadius;
    float smokeBouyancy;
    float smokeWeight;
    float ambientTemperature;
    float impulseTemperature;
    float temperatureDissipation;
    float velocityDissipation;
    float densityDissipation;
    float gradientScale;
    float impulseDensity;
    float obstacleRadius;
    float noiseWeight;
    glm::vec2 obstaclePosition;
    int numJacobiIterations;
    glm::vec2 position;

    sgl::Slab2D velocity;
    sgl::Slab2D density;
    sgl::Slab2D pressure;
    sgl::Slab2D temperature;
    sgl::Surface2D divergence;
    sgl::Surface2D obstacles;
    sgl::Slab2D noise;

    // Ensure we don't double allocate.
    // See note in resource.h
    sgl::Shader subtractShader;
    sgl::Shader jacobiShader;
    sgl::Shader advectShader;
    sgl::Shader impulseShader;
    sgl::Shader divergenceShader;
    sgl::Shader bouyancyShader;
    sgl::Shader obstacleShader;
    sgl::Shader textureShader;

    sgl::MeshResource renderQuad;

    SimState (size_t w, size_t h) :
        width(w), height(h),
        gridWidth(w),
        gridHeight(h),
        renderQuad(sgl::createPlane()),
        velocity(createSlab(w,h,2)),
        density(createSlab(w,h,1)),
        pressure(createSlab(w,h,1)),
        temperature(createSlab(w,h,1)),
        divergence(createSurface(w,h,3)),
        obstacles(createSurface(w,h,3)),
        noise(createSlab(w,h,2)),
        noiseWeight(0.00001f),
        timeStep(0.01f),
        cellSize(1.25f),
        smokeBouyancy(1.0f),
        smokeWeight(0.05f),
        gradientScale(1.125f / cellSize),
        temperatureDissipation(0.99f),
        ambientTemperature(1.0f),
        velocityDissipation(0.99f),
        densityDissipation(0.9999f),
        splatRadius(gridWidth / 8.0f),
        impulseDensity(2),
        impulseTemperature(10.f),
        obstacleRadius(0.2),
        obstaclePosition(0.5f,0.5f),
        numJacobiIterations(10),
        position(gridWidth / 2, gridWidth / 2)

    {
        // More efficient than loading the same file and recompiling the vertex shader for
        // each shader that we have.
        std::string fragSource = sgl::loadShaderSource(TEST_RES("fluid_fs.glsl"));
        sgl::VertexShader identShader = sgl::loadShaderStage<GL_VERTEX_SHADER>(TEST_RES("ident_vs.glsl"));
        linkShader(subtractShader  , identShader, fragSource, "SUBTRACT_SHADER");
        linkShader(jacobiShader    , identShader, fragSource, "JACOBI_SHADER");
        linkShader(advectShader    , identShader, fragSource, "ADVECT_SHADER");
        linkShader(impulseShader   , identShader, fragSource, "IMPULSE_SHADER");
        linkShader(divergenceShader, identShader, fragSource, "DIVERGENCE_SHADER");
        linkShader(bouyancyShader  , identShader, fragSource, "BOUYANCY_SHADER");
        linkShader(obstacleShader  , identShader, fragSource, "OBSTACLE_SHADER");
        linkShader(textureShader   , identShader, fragSource, "VISUALIZE_SHADER");
    }

    void release () {
        subtractShader.release();
        jacobiShader.release();
        advectShader.release();
        impulseShader.release();
        divergenceShader.release();
        bouyancyShader.release();
        obstacleShader.release();
        textureShader.release();
        velocity.release();
        density.release();
        temperature.release();
        pressure.release();
        obstacles.release();
        divergence.release();
        renderQuad.release();
        fbo.release();
    }

private:
    void linkShader (sgl::Shader& shader, sgl::VertexShader& vs, const std::string& src, const std::string& type){
        const std::string& ver = "#version 330 core\n";
        sgl::FragmentShader frag = sgl::compileShaderStage<GL_FRAGMENT_SHADER>({ver, "#define ", type, "\n", src}, type);
        sgl::linkShaderStages(shader, vs, frag);
    }
};

template <GLenum kind>
void visualize (SimState& state, sgl::GLResource<kind>& texture){
    static_assert(sgl::traits::IsTex2D<kind>::value, "Texture must be a texture2D instance");
    glViewport(0, 0, state.width, state.height);
    sgl::bind<GL_FRAMEBUFFER>(0);
    glClearColor(0,0,0,1);
    glClear(GL_COLOR_BUFFER_BIT);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    state.textureShader.bind();
    state.textureShader.setTexture("image", texture, 0);
    state.textureShader.setUniform3fv("fillColor", 1, 1, 1);
    state.textureShader.setUniform2fv("scale", 1.f / state.width, 1.f / state.height);
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);

    glDisable(GL_BLEND);
    sglDbgCatchGLError();
}

void initObstacles (SimState& state, sgl::Surface2D& dest) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.obstacleShader.bind();
    state.obstacleShader.setUniform2fv("position", state.obstaclePosition.x, state.obstaclePosition.y);
    state.obstacleShader.setUniform4fv("color", 1, 0, 0, 0);
    state.obstacleShader.setUniform1f("radius", state.obstacleRadius);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applyAdvect (
    SimState& state,
    sgl::Surface2D& velocity, sgl::Surface2D& source,
    sgl::Surface2D& obstacles, sgl::Surface2D& dest,
    float dissipation
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.advectShader.bind();
    state.advectShader.setTexture("VelocityTexture", velocity.texture, 0);
    state.advectShader.setTexture("SourceTexture", source.texture, 1);
    state.advectShader.setTexture("Obstacles", obstacles.texture, 2);
    state.advectShader.setUniform2fv("InverseSize", 1.f / state.width, 1.f / state.height);
    state.advectShader.setUniform1f("TimeStep", state.timeStep);
    state.advectShader.setUniform1f("Dissipation", dissipation);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applyBouyancy (
    SimState& state,
    sgl::Surface2D& velocity, sgl::Surface2D& temperature,
    sgl::Surface2D& density, sgl::Surface2D& dest
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.bouyancyShader.bind();
    state.bouyancyShader.setTexture("velocityTexture", velocity.texture, 0);
    state.bouyancyShader.setTexture("tempTexture", temperature.texture, 1);
    state.bouyancyShader.setTexture("densityTexture", density.texture, 2);
    state.bouyancyShader.setUniform1f("ambientTemperature", state.ambientTemperature);
    state.bouyancyShader.setUniform1f("timeStep", state.timeStep);
    state.bouyancyShader.setUniform1f("sigma", state.smokeBouyancy);
    state.bouyancyShader.setUniform1f("kappa", state.smokeWeight);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applyDivergence (
    SimState& state,
    sgl::Surface2D& velocity, sgl::Surface2D& obstacle,
    sgl::Surface2D& dest
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.divergenceShader.bind();
    state.divergenceShader.setTexture("Velocity", velocity.texture, 0);
    state.divergenceShader.setTexture("Obstacles", obstacle.texture, 1);
    state.divergenceShader.setUniform1f("HalfInverseCellSize", 0.5f / state.cellSize);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applyImpulse (
    SimState& state,
    sgl::Surface2D& dest,
    glm::vec2& pos, float value, float radExtra = 0
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.impulseShader.bind();
    state.impulseShader.setUniform1f("radius", state.splatRadius + radExtra);
    state.impulseShader.setUniform2fv("point", pos.x, pos.y);
    state.impulseShader.setUniform3fv("fillColor", value, value, value);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applyJacobi (
    SimState& state,
    sgl::Surface2D& pressure, sgl::Surface2D& divergence,
    sgl::Surface2D& obstacle, sgl::Surface2D& dest
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.jacobiShader.bind();
    state.jacobiShader.setTexture("Pressure", pressure.texture, 0);
    state.jacobiShader.setTexture("Divergence", divergence.texture, 1);
    state.jacobiShader.setTexture("Obstacles", obstacle.texture, 2);
    state.jacobiShader.setUniform1f("Alpha", -state.cellSize * state.cellSize);
    state.jacobiShader.setUniform1f("InverseBeta", 0.25f);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

void applySubtract (
    SimState& state,
    sgl::Surface2D& velocity, sgl::Surface2D& pressure,
    sgl::Surface2D& obstacle, sgl::Surface2D& dest
) {
    auto bg = sgl::bind_guard(dest.fbo);

    state.subtractShader.bind();
    state.subtractShader.setTexture("Velocity", velocity.texture, 0);
    state.subtractShader.setTexture("Pressure", pressure.texture, 1);
    state.subtractShader.setTexture("Obstacles", obstacle.texture, 2);
    state.subtractShader.setUniform1f("GradientScale", state.gradientScale);

    state.renderQuad.bind();
    glDrawElements(GL_TRIANGLES, state.renderQuad.size, GL_UNSIGNED_INT, 0);
    sglDbgCatchGLError();
}

int main () {
    sgl::Context ctx(500,900,"fluid sim");
    SimState state(ctx.attrs.width, ctx.attrs.height);

    const char * slabNames [] = {
        "velocity", "temperature",
        "density", "pressure", "divergence",
        "noise"
    };

    sgl::Surface2D slabs[] = {
        state.velocity.ping(),
        state.temperature.ping(),
        state.density.ping(),
        state.pressure.ping(),
        state.divergence,
        state.noise.ping()
    };

    sgl::Param<int> renderStage{"render stage"};
    sgl::Param<int> currentSlab{"current slab", &sgl::ListPrinter<int,char*>::print, slabNames};
    sgl::Param<float&> timeStep{"time step",state.timeStep, 0.01f};
    sgl::Param<float&> ambientTemp{"ambient temperature", state.ambientTemperature, 0.01f};
    sgl::Param<float&> tempDisp {"temperature dissipation", state.temperatureDissipation, 0.01f};
    sgl::Param<float&> densityDisp {"density dissipation", state.densityDissipation, 0.01f};
    sgl::Param<float&> impulseTemp{"impulse temperature", state.impulseTemperature, 0.1f};
    sgl::Param<float&> impulseDensity {"impulse density", state.impulseDensity, 0.1f};
    sgl::Param<int&> jacobiIters{"jacobi iterations", state.numJacobiIterations, 1};
    sgl::Param<float&> splatRadius{"splat radius", state.splatRadius, 1.f};
    sgl::Param<float&> gradientScale{"gradient scale", state.gradientScale, 0.01f};
    sgl::Param<float&> smokeWeight{"smoke weight", state.smokeWeight, 0.01f};
    sgl::Param<float&> smokeBouyancy{"smoke bouyancy", state.smokeBouyancy, 0.01f};
    sgl::Param<float&> velocityDisp {"velociy dissipation", state.velocityDissipation, 0.01f};
    sgl::Param<float&> cellSize{"cell size", state.cellSize, 0.01f};
    sgl::Param<bool> advectDensity{"advect density", true};
    sgl::Param<bool> advectTemperature{"advect temperature", true};
    sgl::Param<bool> advectVelocity{"advect velocity", true};
    bool continueRendering = true;

    renderStage.set(4);
    currentSlab.set(3);
    advectTemperature.set(true);
    advectDensity.set(true);
    advectVelocity.set(true);

    ctx.addMouseHandler(sgl::SimpleDragger{[&state](const sgl::DragEvent& event) {
        state.position = {event.mx, state.height - event.my};
    }});

    ctx.addKeyHandler([
        &currentSlab, &timeStep, &ambientTemp,
        &impulseTemp, &jacobiIters, &splatRadius,
        &renderStage,&gradientScale,&smokeWeight,
        &velocityDisp, &impulseDensity, &tempDisp,
        &smokeBouyancy, &densityDisp, &cellSize,
        &continueRendering, &advectDensity, &advectTemperature,
        &advectVelocity](const sgl::KeyEvent& evt) {
        if (evt.eventType != sgl::RELEASE && evt.eventType != sgl::REPEAT) return;
        if (evt.key == sgl::KEY_A) currentSlab.set((currentSlab + 1) % 6);
        else if (evt.key == sgl::KEY_Q) renderStage.set((renderStage + 1) % 5);
        else if (evt.key == sgl::KEY_Z) evt.shiftPressed ? timeStep.decrement() : timeStep.increment();
        else if (evt.key == sgl::KEY_M) evt.shiftPressed ? ambientTemp.decrement() : ambientTemp.increment();
        else if (evt.key == sgl::KEY_C) evt.shiftPressed ? impulseTemp.decrement() : impulseTemp.increment();
        else if (evt.key == sgl::KEY_J) evt.shiftPressed ? jacobiIters.decrement() : jacobiIters.increment();
        else if (evt.key == sgl::KEY_R) evt.shiftPressed ? splatRadius.decrement() : splatRadius.increment();
        else if (evt.key == sgl::KEY_G) evt.shiftPressed ? gradientScale.decrement() : gradientScale.increment();
        else if (evt.key == sgl::KEY_W) evt.shiftPressed ? smokeWeight.decrement() : smokeWeight.increment();
        else if (evt.key == sgl::KEY_V) evt.shiftPressed ? velocityDisp.decrement() : velocityDisp.increment();
        else if (evt.key == sgl::KEY_D) evt.shiftPressed ? impulseDensity.decrement() : impulseDensity.increment();
        else if (evt.key == sgl::KEY_T) evt.shiftPressed ? tempDisp.decrement() : tempDisp.increment();
        else if (evt.key == sgl::KEY_B) evt.shiftPressed ? smokeBouyancy.decrement() : smokeBouyancy.increment();
        else if (evt.key == sgl::KEY_L) evt.shiftPressed ? densityDisp.decrement() : densityDisp.increment();
        else if (evt.key == sgl::KEY_S) evt.shiftPressed ? cellSize.decrement() : cellSize.increment();
        else if (evt.key == sgl::KEY_ESCAPE) continueRendering = false;
        else if (evt.key == sgl::KEY_1) advectDensity.set(!advectDensity.get());
        else if (evt.key == sgl::KEY_2) advectVelocity.set(!advectVelocity.get());
        else if (evt.key == sgl::KEY_3) advectTemperature.set(!advectTemperature.get());
    });

    /*
    random_bytes_engine rbe;
    std::vector<unsigned char> data(state.noise.ping().texture.attrs.size());
    std::generate(begin(data), end(data), std::ref(rbe));
    */

    //sgl::updateTexture(state.velocity.ping().texture, data.data(), 0, 0);
    //sgl::updateTexture(state.temperature.ping().texture, data.data(), 0, 0);
    //sgl::updateTexture(state.density.ping().texture, data.data(), 0, 0);
    //sgl::updateTexture(state.noise.ping().texture, data.data(), 0, 0);

    //clearColor(state.density.ping().fbo, 1, 0, 0, 1);
    clearColor(state.temperature.ping().fbo, state.ambientTemperature);

    initObstacles(state, state.obstacles);

    glViewport(0,0,state.width, state.height);

    while (ctx.isAlive()){
        ctx.pollEvents();
        if (advectVelocity) {
            applyAdvect(state,
                state.velocity.ping(), state.velocity.ping(),
                state.obstacles, state.velocity.pong(),
                state.velocityDissipation
            );
            state.velocity.swap();
        }

        if (advectTemperature){
            applyAdvect(
                state,
                state.velocity.ping(), state.temperature.ping(),
                state.obstacles, state.temperature.pong(),
                state.temperatureDissipation
            );
            state.temperature.swap();
        }

        if (advectDensity) {
            applyAdvect(
                state,
                state.velocity.ping(), state.density.ping(),
                state.obstacles, state.density.pong(),
                state.densityDissipation
            );
            state.density.swap();
        }

        applyBouyancy(
            state,
            state.velocity.ping(), state.temperature.ping(),
            state.density.ping(), state.velocity.pong()
        );
        state.velocity.swap();

        if (renderStage == 1) { visualize(state, slabs[currentSlab].texture); goto end;}

        applyImpulse(state, state.temperature.ping(), state.position, state.impulseTemperature);
        applyImpulse(state, state.density.ping(), state.position, state.impulseDensity);
        applyDivergence(state, state.velocity.ping(), state.obstacles, state.divergence);

        if (renderStage == 2) { visualize(state, slabs[currentSlab].texture); goto end;}

        clearColor(state.pressure.ping().fbo, 0, 0, 0, 0);

        for (int i = 0; i < state.numJacobiIterations; i++){
            applyJacobi(state, state.pressure.ping(), state.divergence, state.obstacles, state.pressure.pong());
            state.pressure.swap();
        }

        if (renderStage == 3) { visualize(state, slabs[currentSlab].texture); goto end;}

        applySubtract(
            state,
            state.velocity.ping(), state.pressure.ping(),
            state.obstacles, state.velocity.pong()
        );
        state.velocity.swap();

        visualize(state, slabs[currentSlab].texture);
end:
        ctx.swapBuffers();
    }
}


Candle Holders. Though this requirement to secure wax lights safely is a significant concern, candle retailers are considering more often users are buying candle holders for giving purpose, table centre items or even to balance their décor. By itself, there is a requirement for action for decorative stands to keep such enchanting torches. According to the demand of the market, popular candle retailers have developed glass as well as ceramic spots according to the tastes of the clients. You can ideally make a the choice from following factors: Tea light holders. Tea light holders surely produce a wonderful charm to any place and simply add a touch of coolness to your home. Decorative Candle Holders can turn distinguish wedding ceremony favours or wonderful concept to add up an element of devotion into darker fall weddings simply as table design, and are an amazing gift that one may easily reused time and time again. They are presented in various styles, colours and in many cases shape to steadily place each single tea light, turning them a pleasant intensity for any space. There are various ranges on the market to select from which include handcrafted designs, seasonal themes, mosaic finishes, and coloured wine glass displays to simply amaze your environment.
Nemiri - Retail display rack ebay. Find great deals on ebay for retail display rack shop with confidence skip to main content ebay logo: acrylic clear display retail show stand holder rack for glasses sunglasses see more like this leviton silver retail display rack for blister packs 4 level 38 1 2" 16050 wp see more like this. Retail display rack ebay. Hanging chip & snack display rack, concession, retail, 1 strip condition is used listing is for one strip all that are available are shown i will send the one that has the most clips on it as ther. Retail display racks ebay. Find great deals on ebay for retail display racks shop with confidence skip to main content ebay logo: retail display racks white metal with 4 adjustable shelves 2 pack brand new $ buy it now leviton decora wallplate retail display rack 16050 srs see more like this 2 standing sunglass display rack retail store fixture. Retail clothing display racks ebay. Find great deals on ebay for retail clothing display racks shop with confidence skip to main content ebay logo: 4 way chrome clothing garment retail display rack clothes hanger fixture 72'' see more like this leave feedback about your ebay search experience opens in new window or tab additional site navigation. Display rack ebay. Hanging chip & snack display rack, concession, retail, 1 strip condition is used listing is for one strip all that are available are shown i will send the one that has the most clips on it as there are 2 with 12 clips, one with 11 and one with 10 in used condition. Retail display rack ebay. Find great deals on ebay for retail display rack shop with confidence. Display racks ebay. Find great deals on ebay for display racks shop with confidence skip to main content ebay logo: display grid rack 3 pack 5 ft white retail metal stand wall store wire organizer see more like this sponsored us jewelry velvet necklace chain display stand organizer rack storage holder jr1. Retail display rack ebay. 5,950 results for retail display rack save retail display rack to get e mail alerts and updates on your ebay feed unfollow retail display rack to stop getting updates on your ebay feed. Display rack in retail & shop displays ebay. Buy display rack in retail & shop displays and get the best deals at the lowest prices on ebay! great savings free delivery collection on many items. : display racks retail displays & racks. Retail display fixtures come in multiple forms, such as stands, racks, shelves, and store displays a display rack, also known as retail racks, may hold magazines or other paper documents counter display stands are retail shelving units that typically sit atop a counter or shelf at waist level.


I'm interested in purchasing a home with the Sundance 2710 floor plan. Please contact me.
I'm interested in learning more about the Sundance 2710 floor plan. Please contact me.
I love the home! I love the layout, how everything flows, and the big island in the kitchen. I just love it! Because I loved the house! When I walked in, it was (more…) everything I wanted!
2x6 walls, good size bedrooms, finished garage, roominess, availability, and price.
We love the use of space. We have a huge home, lots of closet space, open kitchen. We felt it was a lot of house for what we paid and are happy about that.
I like the size and space we have. I love the floor plan and how the house is laid out. I also liked that it is way more efficient than my last house and I feel (more…) like it will be a good home to raise / grow my family in.
I like our floorplan, all the windows, color of the home inside and out. Very easy home to make as dressed up as you want. My favorite process of buying the hom (more…) e was the Design Center experience, thank you it was great to be able to pick colors for our new home. We love our new home!
My wife and I chose everything about the home and the end result was better than we expected!
Just bought a house with this floor plan and its amazing! My 2 kids have their own room, plus a guest room and an office for my husband! Huge amazing kitchen and all the closets are big, especially the master!
We have lived in our Sundance for 3 years now and we love it! All of the rooms are large and the master is massive! Great floor plan, indeed.
We have lived in our home now for a little over 3yrs now. Still Love everything about it. Our family has grown since we bought the place, but we still have room! We look forward to the next 20yrs in our home!
My husband and I chose the Sundance for the great spaces to accommodate our 7 children, the loft provides an additional entertainment area for them so that everyone is happy! We also love our bedroom oasis with the huge walk in closet! And everyone who comes into our house is envious of our large kitchen. Great layout!
Please leave us a review about the Sundance 2710.